<template>
    <div class="dashboard-container">
        <!-- 顶部欢迎区域 -->
        <div class="welcome-section">
            <el-row :gutter="20">
                <el-col :xs="24" :sm="24" :md="18">
                    <div class="welcome-card">
                        <div class="welcome-content">
                            <h2>{{ adminInfo.nickname + t('utils.comma') + getGreet() }}</h2>
                        </div>
                        <div class="welcome-image">
                            <img :src="headerSvg" alt="welcome" />
                        </div>
                    </div>
                </el-col>
                <el-col :xs="24" :sm="24" :md="6" class="work-status-col">
                    <div class="work-status-card">
                        <div class="work-status-content">
                            <div class="work-time">
                                <el-icon><Timer /></el-icon>
                                <span>{{ t('dashboard.You have worked today') }}</span>
                                <span class="time">{{ state.workingTimeFormat }}</span>
                            </div>
                            <el-button type="primary" @click="onChangeWorkState()">
                                <el-icon>
                                    <component :is="state.pauseWork ? VideoPlay : Coffee" />
                                </el-icon>
                                {{ state.pauseWork ? t('dashboard.Continue to work') : t('dashboard.have a bit of rest') }}
                            </el-button>
                        </div>
                    </div>
                </el-col>
            </el-row>
        </div>

        <!-- 数据概览卡片 -->
        <div class="data-overview">
            <el-row :gutter="20">
                <el-col :xs="24" :sm="12" :md="12" :lg="6" v-for="(item, index) in dataCards" :key="index">
                    <el-card shadow="hover" class="data-card">
                        <div class="data-card-content">
                            <div class="data-icon">
                                <el-icon><component :is="item.icon" /></el-icon>
                            </div>
                            <div class="data-info">
                                <div class="data-title">{{ item.title }}</div>
                                <div class="data-value">
                                    <el-statistic :value="item.value" :value-style="statisticValueStyle" />
                                </div>
                            </div>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </div>

    </div>
</template>

<script setup lang="ts">
import { useTransition } from '@vueuse/core'
import { CSSProperties, nextTick, onActivated, onBeforeMount, onMounted, onUnmounted, reactive, toRefs, watch, ref, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import headerSvg from '/@/assets/dashboard/header-1.svg'
import { useAdminInfo } from '/@/stores/adminInfo'
import { useNavTabs } from '/@/stores/navTabs'
import { fullUrl, getGreet } from '/@/utils/common'
import { index } from '/@/api/backend/dashboard'
import { Timer, Histogram, View, Calendar, DataLine, ArrowUp, ArrowDown, VideoPlay, Coffee } from '@element-plus/icons-vue'

let workTimer: ReturnType<typeof setInterval>
defineOptions({
    name: 'dashboard',
})

const d = new Date()
const { t } = useI18n()
const navTabs = useNavTabs()
const adminInfo = useAdminInfo()

const state: {
    remark: string
    workingTimeFormat: string
    pauseWork: boolean
    yesterday_trend: number
    today_trend: number
    month_trend: number
    total_trend: number
    startTime: number
    week_visits: number[]
    week_growth_rates: string[]
    hourly_visits: number[]
    updateCountdown: number
} = reactive({
    remark: 'dashboard.Loading',
    workingTimeFormat: '00:00:00',
    pauseWork: false,
    yesterday_trend: 5,
    today_trend: 15,
    month_trend: 8,
    total_trend: 100,
    startTime: Date.now(),
    week_visits: [150, 230, 224, 218, 135, 147, 260],
    week_growth_rates: ['+20', '+32', '-18', '-5', '+25', '+38', '+40'],
    hourly_visits: [120, 82, 201, 234, 190, 330, 410, 320],
    updateCountdown: 60,
})

const chartTimeRange = ref('week')

/**
 * 带有数字向上变化特效的数据
 */
const countUp = reactive({
    userTotal: 0,
    questionTotal: 0,
    courseTotal: 0,
    activity: 0,
    questionUserTotal: 0,
})

index().then((res) => {
    state.remark = res.data.remark
    countUp.userTotal = res.data.userTotal
    countUp.questionTotal = res.data.questionTotal
    countUp.courseTotal = res.data.courseTotal
    countUp.activity = res.data.activity
    countUp.questionUserTotal = res.data.questionUserTotal
})



const countUpRefs = toRefs(countUp)
const userTotalOutput = useTransition(countUpRefs.userTotal, { duration: 1000 })
const questionTotalOutput = useTransition(countUpRefs.questionTotal, { duration: 1000 })
const courseTotalOutput = useTransition(countUpRefs.courseTotal, { duration: 1000 })
const activityOutput = useTransition(countUpRefs.activity, { duration: 1000 })
const questionUserTotalOutput = useTransition(countUpRefs.questionUserTotal, { duration: 1000 })
const statisticValueStyle: CSSProperties = {
    fontSize: '28px',
}


// 格式化时间
const formatTime = (seconds: number): string => {
    const hours = Math.floor(seconds / 3600)
    const minutes = Math.floor((seconds % 3600) / 60)
    const remainingSeconds = seconds % 60

    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 更新工作时间
const updateWorkingTime = () => {
    const currentTime = Date.now()
    const elapsedSeconds = Math.floor((currentTime - state.startTime) / 1000)
    state.workingTimeFormat = formatTime(elapsedSeconds)
}


// 手动更新倒计时（每秒减1，用于显示）
const updateCountdown = () => {
    setInterval(() => {
        if (state.updateCountdown > 0) {
            state.updateCountdown--
        } else {
            state.updateCountdown = 60
        }
    }, 1000)
}


onMounted(() => {
    // 启动工作时间计时器
    workTimer = setInterval(updateWorkingTime, 1000)


    // 启动倒计时更新
    updateCountdown()

})


// 在组件卸载时清理资源
onUnmounted(() => {
    clearInterval(workTimer)
})

// 工作状态切换
const onChangeWorkState = () => {
    state.pauseWork = !state.pauseWork
    if (state.pauseWork) {
        clearInterval(workTimer)
    } else {
        state.startTime = Date.now() - (Date.now() - state.startTime) // 保持暂停前的时间
        workTimer = setInterval(updateWorkingTime, 1000)
    }
}

// 数据卡片配置
const dataCards = computed(() => [
    {
        title: t('会员总量'),
        icon: Histogram,
        value: userTotalOutput.value,
        trend: state.yesterday_trend,
    },
    {
        title: t('调查问券数量'),
        icon: View,
        value: questionTotalOutput.value,
        trend: state.today_trend,
    },
    {
        title: t('视频总数'),
        icon: Calendar,
        value: courseTotalOutput.value,
        trend: state.month_trend,
    },
    {
        title: t('回答问券人数'),
        icon: DataLine,
        value: questionUserTotalOutput.value,
        trend: state.total_trend,
    },
    {
        title: t('活动人数'),
        icon: DataLine,
        value: activityOutput.value,
        trend: state.total_trend,
    },
])
</script>

<style lang="scss" scoped>
.dashboard-container {
    padding: 20px;
    min-height: 100vh;

    @media screen and (max-width: 768px) {
        padding: 10px;
    }

    .welcome-section {
        margin-bottom: 20px;

        @media screen and (max-width: 768px) {
            margin-bottom: 15px;
        }

        .welcome-card,
        .work-status-card {
            height: 128px; // 设置固定高度，使两个卡片高度一致
            display: flex;
            flex-direction: column;
            justify-content: center;

            @media screen and (max-width: 1200px) {
                height: auto;
                min-height: 128px;
            }
        }

        .welcome-card {
            background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
            border-radius: 8px;
            padding: 24px;
            color: white;
            display: flex;
            flex-direction: row;
            justify-content: space-between;
            align-items: center;

            @media screen and (max-width: 768px) {
                padding: 16px;
                flex-direction: column;
                text-align: center;
                gap: 16px;
                height: auto;
            }

            .welcome-content {
                h2 {
                    margin: 0 0 12px 0;
                    font-size: 24px;

                    @media screen and (max-width: 768px) {
                        font-size: 20px;
                    }
                }

                p {
                    margin: 0;
                    opacity: 0.8;
                }
            }

            .welcome-image {
                img {
                    height: 80px;

                    @media screen and (max-width: 768px) {
                        height: 60px;
                    }
                }
            }
        }

        .work-status-col {
            @media screen and (max-width: 768px) {
                display: none;
            }
        }

        .work-status-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            position: relative;
            overflow: hidden;

            @media screen and (max-width: 1200px) {
                padding: 16px;
            }

            @media screen and (max-width: 768px) {
                margin-top: 15px;
                min-height: 140px;
                display: flex;
                align-items: center;
            }

            &::before {
                content: '';
                position: absolute;
                top: 0;
                right: 0;
                width: 120px;
                height: 120px;
                background: url('/@/assets/dashboard/coffee.svg') no-repeat center;
                background-size: contain;
                opacity: 0.1;
                transform: translate(20px, -20px);

                @media screen and (max-width: 768px) {
                    width: 100px;
                    height: 100px;
                    transform: translate(10px, -10px);
                    opacity: 0.05;
                }
            }

            .work-status-content {
                display: flex;
                flex-direction: column;
                gap: 20px;
                position: relative;
                z-index: 1;
                width: 100%;

                @media screen and (max-width: 1200px) {
                    gap: 15px;
                }

                @media screen and (max-width: 768px) {
                    gap: 12px;
                }

                .work-time {
                    display: flex;
                    align-items: center;
                    flex-wrap: wrap;
                    gap: 8px;
                    color: #606266;
                    padding: 12px;
                    background: #f5f7fa;
                    border-radius: 6px;
                    transition: all 0.3s ease;
                    min-height: 44px;

                    @media screen and (max-width: 1200px) {
                        padding: 10px;
                        flex-direction: row;
                        justify-content: space-between;
                        width: 100%;
                    }

                    @media screen and (max-width: 768px) {
                        justify-content: space-between;

                        span:not(.time) {
                            flex: 1;
                            min-width: 0;
                            white-space: nowrap;
                            overflow: hidden;
                            text-overflow: ellipsis;
                        }
                    }

                    &:hover {
                        background: #ecf5ff;
                    }

                    .el-icon {
                        font-size: 20px;
                        color: #409eff;
                        flex-shrink: 0;

                        @media screen and (max-width: 768px) {
                            font-size: 18px;
                        }
                    }

                    span {
                        @media screen and (max-width: 1200px) {
                            font-size: 14px;
                        }

                        @media screen and (max-width: 768px) {
                            font-size: 13px;
                        }
                    }

                    .time {
                        font-weight: bold;
                        color: #409eff;
                        font-size: 18px;
                        font-family: 'Monaco', monospace;
                        margin-left: auto;
                        flex-shrink: 0;

                        @media screen and (max-width: 1200px) {
                            font-size: 16px;
                        }

                        @media screen and (max-width: 768px) {
                            font-size: 15px;
                            margin-left: 0;
                        }
                    }
                }

                .el-button {
                    width: 100%;
                    height: 40px;
                    border-radius: 6px;
                    font-size: 14px;
                    transition: all 0.3s ease;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;

                    @media screen and (max-width: 1200px) {
                        font-size: 13px;
                        padding: 8px 12px;
                        height: 36px;
                    }

                    @media screen and (max-width: 768px) {
                        padding: 8px 15px;
                    }

                    &:hover {
                        transform: translateY(-2px);
                        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
                    }

                    .el-icon {
                        margin-right: 6px;
                        font-size: 16px;

                        @media screen and (max-width: 1200px) {
                            font-size: 15px;
                            margin-right: 4px;
                        }

                        @media screen and (max-width: 768px) {
                            font-size: 14px;
                        }
                    }
                }
            }
        }
    }

    .data-overview {
        margin-bottom: 20px;

        @media screen and (max-width: 768px) {
            margin-bottom: 15px;

            :deep(.el-col) {
                margin-bottom: 10px;

                &:last-child {
                    margin-bottom: 0;
                }
            }
        }

        .data-card {
            margin-bottom: 20px;
            transition: transform 0.3s ease;

            &:hover {
                transform: translateY(-2px);
            }

            .data-card-content {
                display: flex;
                align-items: center;
                gap: 16px;

                @media screen and (max-width: 768px) {
                    gap: 10px;
                }

                .data-icon {
                    width: 48px;
                    height: 48px;
                    border-radius: 8px;
                    background: #ecf5ff;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    flex-shrink: 0;

                    @media screen and (max-width: 768px) {
                        width: 36px;
                        height: 36px;
                    }

                    .el-icon {
                        font-size: 24px;
                        color: #409eff;

                        @media screen and (max-width: 768px) {
                            font-size: 18px;
                        }
                    }
                }

                .data-info {
                    flex: 1;
                    min-width: 0;

                    .data-title {
                        font-size: 14px;
                        color: #909399;
                        margin-bottom: 8px;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;

                        @media screen and (max-width: 768px) {
                            font-size: 12px;
                            margin-bottom: 4px;
                        }
                    }

                    .data-value {
                        display: flex;
                        align-items: baseline;
                        gap: 8px;
                        flex-wrap: wrap;

                        @media screen and (max-width: 768px) {
                            gap: 6px;
                        }

                        :deep(.el-statistic__content) {
                            @media screen and (max-width: 768px) {
                                font-size: 20px !important;
                            }
                        }

                        .data-trend {
                            display: flex;
                            align-items: center;
                            gap: 4px;
                            font-size: 14px;
                            white-space: nowrap;

                            @media screen and (max-width: 768px) {
                                font-size: 12px;
                            }

                            .el-icon {
                                @media screen and (max-width: 768px) {
                                    font-size: 12px;
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    .notice-list {
        .notice-item {
            display: flex;
            align-items: flex-start;
            padding: 12px 0;
            cursor: pointer;
            transition: background-color 0.2s ease;
            border-bottom: 1px solid var(--el-border-color-lighter);

            &:last-child {
                border-bottom: none;
            }

            &:hover {
                background-color: var(--el-fill-color-light);
            }
        }

        .notice-avatar {
            margin-right: 12px;
            flex-shrink: 0;
        }

        .notice-content {
            flex: 1;
            min-width: 0;

            .notice-title {
                display: flex;
                align-items: center;
                justify-content: space-between;
                margin-bottom: 4px;

                .name {
                    font-size: 14px;
                    font-weight: 500;
                    color: var(--el-text-color-primary);
                }

                .time {
                    font-size: 12px;
                    color: var(--el-text-color-secondary);
                }
            }

            .notice-text {
                font-size: 13px;
                color: var(--el-text-color-regular);
                line-height: 1.5;
                overflow: hidden;
                text-overflow: ellipsis;
                display: -webkit-box;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
            }
        }
    }

    .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
}
</style>
